﻿namespace com.stifel.ServerBuildMgmtDao
{
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.SharePoint.Linq;

    using Context = StifelServerBuildDataContext;

    using CustomObject = StifelAgent;

    public class StifelBackupAgentDao : StifelBaseDao
    {
        #region Fields

        public const string ListName = "stifelbkupagents";

        #endregion Fields

        #region Constructors

        public StifelBackupAgentDao( )
            : base(ListName)
        {
            //CurrentWebUrl = SPContext.Current.Web.Url;
            CurrentWebUrl = ConfiguredWebUrl;
        }

        public StifelBackupAgentDao( string currentWebUrl )
            : base(ListName)
        {
            this.CurrentWebUrl = currentWebUrl;
        }

        #endregion Constructors

        #region Methods

        public void Add( CustomObject value )
        {
            using ( Context c = new Context( CurrentWebUrl ) )
            {
                EntityList<CustomObject> l = c.GetList<CustomObject>( ListTitle );
                l.InsertOnSubmit( clean( value ) );
                c.SubmitChanges( );
            }
        }

        public void Clear( )
        {
            using ( Context c = new Context( CurrentWebUrl ) )
            {
                EntityList<CustomObject> l = c.GetList<CustomObject>( ListTitle );
                var v = ( from o in l
                          where o.Id > 0
                          select o );
                if ( v.Count( ) > 0 )
                {
                    l.DeleteAllOnSubmit( v );
                    c.SubmitChanges( );
                }
            }
        }

        public List<CustomObject> GetAll( )
        {
            using ( Context c = new Context( CurrentWebUrl ) )
            {
                List<CustomObject> l = c.GetList<CustomObject>( ListTitle ).ToList( );
                return l;
            }
        }

        public List<CustomObject> GetAllActiveItems( )
        {
            using ( Context c = new Context( CurrentWebUrl ) )
            {
                List<CustomObject> l = c.GetList<CustomObject>( ListTitle ).ToList( );
                List<CustomObject> activel = ( from o in l
                                               where o.AgentActive.Value == true
                                               select o ).ToList( );
                return activel;
            }
        }

        CustomObject clean( CustomObject value )
        {
            return new CustomObject
            {
                AgentActive = value.AgentActive,
                AgentDescription = value.AgentDescription,
                Title = value.Title
            };
        }

        #endregion Methods
    }
}